<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { useUserStore } from '../../stores/modules/user'
import { userUpdateInfoService } from '@/api/user'

// 控制加载效果
const loading = ref(false)
const formRef = ref()
// 是在创库中数据的初始值(无需响应式)
const {
  user: { id, nickname, username, email },
  getUser
} = useUserStore()

const formData = ref({
  id,
  username, // 登录名称输入框禁用
  nickname, // 用户昵称输入框可输入
  email // 用户邮箱输入框可输入
})

const formRules = ref({
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个非空字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱格式',
      trigger: ['blur', 'change']
    }
  ]
})
// 修改按钮
const submitForm = async () => {
  //   预校验
  formRef.value.validate()
  //   console.log(formData.value)
  //   加载打开效果
  loading.value = true
  await userUpdateInfoService(formData.value)
  //   通知user模块 进行数据通知
  getUser()
  ElMessage.success('修改成功')
  //   加载关闭效果
  loading.value = false
}
</script>

<template>
  <page-container title="基本资料">
    <!-- 表单部分 -->
    <el-form
      v-loading="loading"
      :model="formData"
      label-width="100px"
      ref="formRef"
      :rules="formRules"
    >
      <el-form-item label="登录名称">
        <el-input
          v-model="formData.username"
          disabled
          style="width: 250px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formData.nickname" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="formData.email" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交修改</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
